package sound;


import java.io.BufferedInputStream;
import java.io.FileInputStream;

import javazoom.jl.player.Player;


/**
 * Class: Track.java
 * Description: This class loads an MP3 file.
 * Requires the included JAR file.
 * Got this from:
 * http://www.cs.princeton.edu/introcs/faq/mp3/mp3.html
 * @author Princeton
 */

public class Track {
    private String filename;
    private Player player;

    // constructor that takes the name of an MP3 file
    public Track(String filename)
    {
        this.filename = filename;
    }

    public void setFilename(String filename)
    {
        this.filename = filename;
    }

    public void stop()
    {
        if (player != null)
        {
            player.close();
            System.out.println("Stop playing:" + filename);
        }
    }

    public boolean done()
    {
        return player.isComplete();
    }

    public int getPosition()
    {
        return player.getPosition();
    }

    // play the MP3 file to the sound card
    public void play()
    {
        System.out.println("Playing track:" + filename);
        try
        {
            FileInputStream fis = new FileInputStream(filename);
            BufferedInputStream bis = new BufferedInputStream(fis);
            player = new Player(bis);
        }
        catch (Exception e)
        {
            System.out.println("Problem playing file " + filename);
            System.out.println(e);
        }

        // run in new thread to play in background
        new Thread()
        {

            public void run()
            {
                try
                {
                    player.play();
                } catch (Exception e)
                {
                    System.out.println(e);
                }
            }
        }.start();

    }
}

